package com.iflytek.uoamp.agent.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class WFile {
	private WFile(){
		
	}
	
	private static void createfolder(String strFile){
		if(strFile !=null && strFile.lastIndexOf("/")!=-1){
			File file=new File(strFile.substring(0,strFile.lastIndexOf("/")));
			if(!file.exists()){
				file.mkdirs();
			}
		}
	}
	
	
	public static boolean wf(String file,String content){
		return wf(file,content,"utf-8",false);
	}
	
	public static void wf(String file,String content,boolean isAdd){
		wf(file,content,"utf-8",isAdd);
	}
	
	public static boolean wf(String file,String content,String encoding,boolean isAdd){
		PrintWriter out = null;
		FileOutputStream fo = null;
		OutputStreamWriter os = null;
		BufferedWriter bf = null;
		try {
			fo = new FileOutputStream(file,isAdd);
		} catch (FileNotFoundException e1) {
			Logger.getRootLogger().error("file not exist ",e1);
			createfolder(file);
			try {
				fo = new FileOutputStream(file,isAdd);
			} catch (FileNotFoundException e) {
				Logger.getRootLogger().error("file not exist and create error",e);
				return false;
			}
		}
		try{
			os = new OutputStreamWriter(fo,encoding);
			bf = new BufferedWriter(os);
			out = new PrintWriter(bf);
			out.write(content);
			return true;
		} catch (UnsupportedEncodingException e1) {
			Logger.getRootLogger().error(e1.getMessage(),e1);
			return false;
		}finally{
			try {
				if(out!=null){
					out.close();
				}
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
			}
			try {
				if(bf!=null){
					bf.close();
				}
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
			}
			try {
				if(os!=null){
					os.close();
				}
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
			}
			try {
				if(fo!=null){
					fo.close();
				}
			} catch (Exception e) {
				Logger.getRootLogger().error(e.getMessage(),e);
			}
		}

	}
	
	
	public static boolean wfByByte(String file,byte[] content){
		if(StringUtils.isBlank(file) || null == content) {
			return false;
		}
		
		File wfile = new File(file);

		FileOutputStream oStream = null;
		try {
			oStream = new FileOutputStream(wfile);
		} catch (FileNotFoundException e) {
//			Logger.getRootLogger().info("file not exist ",e);
			createfolder(file);
			try {
				oStream = new FileOutputStream(wfile);
			} catch (FileNotFoundException e1) {
				Logger.getRootLogger().error("havn't file yet,and can't create new file!!  "+file,e1);
				return false;
			}
		} 
		
		try{
			oStream.write(content);		
		}catch (IOException e) {
			Logger.getRootLogger().error("havn't file yet,and can't create new file!!  "+file,e);
			return false;
		} finally {
			if (oStream != null) {
				try {
					oStream.close();
				} catch (IOException e) {
					Logger.getRootLogger().error("havn't file yet,and can't create new file!!  "+file,e);
				}
			}
		}
		return true;
	}
	
    public static boolean unZipFiles(String zipPath,String descDir){  
        return unZipFiles(zipPath, descDir, true);  
    }
    
    public static boolean unZipFiles(String zipPath,String descDir, boolean isLinux){  
        return unZipFiles(new File(zipPath), descDir, isLinux);  
    } 
    
    @SuppressWarnings("rawtypes")  
	public static boolean unZipFiles(File zipFile,String descDir, boolean isLinux){
    	ZipFile zip = null;
    	try{
    		File pathFile = new File(descDir);  
	        if(!pathFile.exists()){  
	            pathFile.mkdirs();  
	        }  
	        zip = new ZipFile(zipFile);  
			for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
				InputStream in = null;
				OutputStream out = null;
				String zipEntryName = "";
				try {
					ZipEntry entry = (ZipEntry) entries.nextElement();
					zipEntryName = entry.getName();
					String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
					// 判断路径是否存在,不存在则创建文件路径
					File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
					if (!file.exists()) {
						file.mkdirs();
					}
					// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
					if (new File(outPath).isDirectory()) {
						continue;
					}
					in = zip.getInputStream(entry);
					out = new FileOutputStream(outPath);
					byte[] buf = new byte[1024];
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
				} catch (Exception e) {
					Logger.getRootLogger().error("unZipFiles occur error -->".concat(zipEntryName), e);
				} finally {
					if (null != in) {
						try {
							in.close();
						} catch (Exception exc) {
							/*ignore*/
						}
					}

					if (null != out) {
						try {
							out.close();
						} catch (Exception exc) {
							/*ignore*/
						}
					}
				}
			}
	        
	    	Logger.getRootLogger().info("unZipFiles success!!!");
	    	if (isLinux) {
	    		Process ps = Runtime.getRuntime().exec("chmod 700 -R cmd");
		    	ps.waitFor();
			}
	    	return true;
	    }catch(Exception e){
	    	Logger.getRootLogger().error("unZipFiles faild!!!"+zipFile,e);
	    	return false;
    	} finally {
    		if (null != zip) {
				try {
					zip.close();
				} catch (Exception e2) {
					/*ignore*/
				}
			}
    	}  
    }	
    
    
    /** 
     * 复制单个文件 
     * @param oldPath String 原文件路径 如：c:/fqf.txt 
     * @param newPath String 复制后路径 如：f:/fqf.txt 
     * @return boolean 
     */ 
	public static boolean copyFile(String oldPath, String newPath) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		int bytesum = 0;
		int byteread = 0;
		try {
			File oldfile = new File(oldPath);
			// 文件存在时
			if (oldfile.exists()) {
				// 读入原文件
				bis = new BufferedInputStream(new FileInputStream(oldPath)); 
				bos = new BufferedOutputStream(new FileOutputStream(newPath));
				byte[] buffer = new byte[1024];
				int length;
				while ((byteread = bis.read(buffer)) != -1) {
					// 字节数文件大小
					bytesum += byteread; 
					bos.write(buffer, 0, byteread);
				}
			}
			return true;
		} catch (Exception e) {
			Logger.getRootLogger().error("copy file faild! src file path-->" + oldPath + "; dest file path-->" + newPath, e);
			return false;
		} finally {
			if (null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					Logger.getRootLogger().error("close inputstream error.", e);
				}
			}
			
			if (null != bos) {
				try {
					bos.close();
				} catch (IOException e) {
					Logger.getRootLogger().error("close outputstream error.", e);
				}
			}
		}
	}
	
	public static boolean copyDirectory(String srcDir, String destDir, FileFilter filter) {
		boolean result = false;
		if (StringUtils.isBlank(srcDir)) {
			return result;
		}
		File srcDirFile = new File(srcDir);
		if (!srcDirFile.exists()) {
			// 源目录不存在，认为复制成功
			return true;
		}
		File destDirFile = new File(destDir);
		try {
			/*FileUtils.*/copyDirectory(srcDirFile, destDirFile, filter, true);
			result = true;
		} catch (IOException e) {
			Logger.getRootLogger().error("copy directory error. -->".concat(srcDir), e);
		}
		return result;
	}
	
	/************************以下方法从commons-io.FileUtils中copy而来****************************/ 
	/**
	 * Copies a filtered directory to a new location.
	 * <p>
	 * This method copies the contents of the specified source directory to
	 * within the specified destination directory.
	 * <p>
	 * The destination directory is created if it does not exist. If the
	 * destination directory did exist, then this method merges the source with
	 * the destination, with the source taking precedence.
	 * <p>
	 * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
	 * {@code true} tries to preserve the files' last modified date/times using
	 * {@link File#setLastModified(long)}, however it is not guaranteed that
	 * those operations will succeed. If the modification operation fails, no
	 * indication is provided.
	 *
	 * <h4>Example: Copy directories only</h4>
	 * 
	 * <pre>
	 * // only copy the directory structure
	 * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
	 * </pre>
	 *
	 * <h4>Example: Copy directories and txt files</h4>
	 * 
	 * <pre>
	 * // Create a filter for &quot;.txt&quot; files
	 * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(&quot;.txt&quot;);
	 * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE,
	 * 		txtSuffixFilter);
	 * 
	 * // Create a filter for either directories or &quot;.txt&quot; files
	 * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY,
	 * 		txtFiles);
	 * 
	 * // Copy using the filter
	 * FileUtils.copyDirectory(srcDir, destDir, filter, false);
	 * </pre>
	 * 
	 * @param srcDir
	 *            an existing directory to copy, must not be {@code null}
	 * @param destDir
	 *            the new directory, must not be {@code null}
	 * @param filter
	 *            the filter to apply, null means copy all directories and files
	 * @param preserveFileDate
	 *            true if the file date of the copy should be the same as the
	 *            original
	 *
	 * @throws NullPointerException
	 *             if source or destination is {@code null}
	 * @throws IOException
	 *             if source or destination is invalid
	 * @throws IOException
	 *             if an IO error occurs during copying
	 * @since 1.4
	 */
	public static void copyDirectory(File srcDir, File destDir,
			FileFilter filter, boolean preserveFileDate) throws IOException {
		if (srcDir == null) {
			throw new NullPointerException("Source must not be null");
		}
		if (destDir == null) {
			throw new NullPointerException("Destination must not be null");
		}
		if (srcDir.exists() == false) {
			throw new FileNotFoundException("Source '" + srcDir
					+ "' does not exist");
		}
		if (srcDir.isDirectory() == false) {
			throw new IOException("Source '" + srcDir
					+ "' exists but is not a directory");
		}
		if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
			throw new IOException("Source '" + srcDir + "' and destination '"
					+ destDir + "' are the same");
		}

		// Cater for destination being directory within the source directory
		// (see IO-141)
		List<String> exclusionList = null;
		if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
			File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir
					.listFiles(filter);
			if (srcFiles != null && srcFiles.length > 0) {
				exclusionList = new ArrayList<String>(srcFiles.length);
				for (File srcFile : srcFiles) {
					File copiedFile = new File(destDir, srcFile.getName());
					exclusionList.add(copiedFile.getCanonicalPath());
				}
			}
		}
		doCopyDirectory(srcDir, destDir, filter, preserveFileDate,
				exclusionList);
	}

	/**
	 * Internal copy directory method.
	 * 
	 * @param srcDir
	 *            the validated source directory, must not be {@code null}
	 * @param destDir
	 *            the validated destination directory, must not be {@code null}
	 * @param filter
	 *            the filter to apply, null means copy all directories and files
	 * @param preserveFileDate
	 *            whether to preserve the file date
	 * @param exclusionList
	 *            List of files and directories to exclude from the copy, may be
	 *            null
	 * @throws IOException
	 *             if an error occurs
	 * @since 1.1
	 */
	private static void doCopyDirectory(File srcDir, File destDir,
			FileFilter filter, boolean preserveFileDate,
			List<String> exclusionList) throws IOException {
		// recurse
		File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir
				.listFiles(filter);
		if (srcFiles == null) { // null if abstract pathname does not denote a
								// directory, or if an I/O error occurs
			throw new IOException("Failed to list contents of " + srcDir);
		}
		if (destDir.exists()) {
			if (destDir.isDirectory() == false) {
				throw new IOException("Destination '" + destDir
						+ "' exists but is not a directory");
			}
		} else {
			if (!destDir.mkdirs() && !destDir.isDirectory()) {
				throw new IOException("Destination '" + destDir
						+ "' directory cannot be created");
			}
		}
		if (destDir.canWrite() == false) {
			throw new IOException("Destination '" + destDir
					+ "' cannot be written to");
		}
		for (File srcFile : srcFiles) {
			File dstFile = new File(destDir, srcFile.getName());
			if (exclusionList == null
					|| !exclusionList.contains(srcFile.getCanonicalPath())) {
				if (srcFile.isDirectory()) {
					doCopyDirectory(srcFile, dstFile, filter, preserveFileDate,
							exclusionList);
				} else {
					doCopyFile(srcFile, dstFile, preserveFileDate);
				}
			}
		}

		// Do this last, as the above has probably affected directory metadata
		if (preserveFileDate) {
			destDir.setLastModified(srcDir.lastModified());
		}
	}

	/**
	 * Internal copy file method.
	 * 
	 * @param srcFile
	 *            the validated source file, must not be {@code null}
	 * @param destFile
	 *            the validated destination file, must not be {@code null}
	 * @param preserveFileDate
	 *            whether to preserve the file date
	 * @throws IOException
	 *             if an error occurs
	 */
	private static void doCopyFile(File srcFile, File destFile,
			boolean preserveFileDate) throws IOException {
		if (destFile.exists() && destFile.isDirectory()) {
			throw new IOException("Destination '" + destFile
					+ "' exists but is a directory");
		}

		FileInputStream fis = null;
		FileOutputStream fos = null;
		FileChannel input = null;
		FileChannel output = null;
		try {
			fis = new FileInputStream(srcFile);
			fos = new FileOutputStream(destFile);
			input = fis.getChannel();
			output = fos.getChannel();
			long size = input.size();
			long pos = 0;
			long count = 0;
			while (pos < size) {
				count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE
						: size - pos;
				pos += output.transferFrom(input, pos, count);
			}
		} finally {
			closeQuietly(output);
			closeQuietly(fos);
			closeQuietly(input);
			closeQuietly(fis);
		}

		if (srcFile.length() != destFile.length()) {
			throw new IOException("Failed to copy full contents from '"
					+ srcFile + "' to '" + destFile + "'");
		}
		if (preserveFileDate) {
			destFile.setLastModified(srcFile.lastModified());
		}
	}

	/**
	 * The number of bytes in a kilobyte.
	 */
	public static final long ONE_KB = 1024;
	/**
	 * The number of bytes in a megabyte.
	 */
	public static final long ONE_MB = ONE_KB * ONE_KB;
	/**
	 * The file copy buffer size (30 MB)
	 */
	private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;

	/**
     * The Unix separator character.
     */
    private static final char UNIX_SEPARATOR = '/';

    /**
     * The Windows separator character.
     */
    private static final char WINDOWS_SEPARATOR = '\\';

    /**
     * The system separator character.
     */
    private static final char SYSTEM_SEPARATOR = File.separatorChar;

	/**
	 * Unconditionally close an <code>InputStream</code>.
	 * <p>
	 * Equivalent to {@link InputStream#close()}, except any exceptions will be
	 * ignored. This is typically used in finally blocks.
	 * <p>
	 * Example code:
	 * 
	 * <pre>
	 * byte[] data = new byte[1024];
	 * InputStream in = null;
	 * try {
	 * 	in = new FileInputStream(&quot;foo.txt&quot;);
	 * 	in.read(data);
	 * 	in.close(); // close errors are handled
	 * } catch (Exception e) {
	 * 	// error handling
	 * } finally {
	 * 	IOUtils.closeQuietly(in);
	 * }
	 * </pre>
	 *
	 * @param input
	 *            the InputStream to close, may be null or already closed
	 */
	public static void closeQuietly(InputStream input) {
		closeQuietly((Closeable) input);
	}

	/**
	 * Unconditionally close an <code>OutputStream</code>.
	 * <p>
	 * Equivalent to {@link OutputStream#close()}, except any exceptions will be
	 * ignored. This is typically used in finally blocks.
	 * <p>
	 * Example code:
	 * 
	 * <pre>
	 * byte[] data = &quot;Hello, World&quot;.getBytes();
	 * 
	 * OutputStream out = null;
	 * try {
	 * 	out = new FileOutputStream(&quot;foo.txt&quot;);
	 * 	out.write(data);
	 * 	out.close(); // close errors are handled
	 * } catch (IOException e) {
	 * 	// error handling
	 * } finally {
	 * 	IOUtils.closeQuietly(out);
	 * }
	 * </pre>
	 *
	 * @param output
	 *            the OutputStream to close, may be null or already closed
	 */
	public static void closeQuietly(OutputStream output) {
		closeQuietly((Closeable) output);
	}

	public static void closeQuietly(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}
	
	
	
	
	
	
	
	/**
     * Deletes a directory recursively. 
     *
     * @param directory  directory to delete
     * @throws IOException in case deletion is unsuccessful
     */
	public static void deleteDirectory(String directory) throws IOException {
		File directoryFile = new File(directory);
		deleteDirectory(directoryFile, false);
	}
	
    public static void deleteDirectory(File directory, boolean deleteRoot) throws IOException {
        if (!directory.exists()) {
            return;
        }

        if (!isSymlink(directory)) {
            cleanDirectory(directory);
        }

        if (deleteRoot && !directory.delete()) {
            String message = "Unable to delete directory " + directory + ".";
            throw new IOException(message);
        }
    }
    
    /**
     * Determines whether the specified file is a Symbolic Link rather than an actual file.
     * <p>
     * Will not return true if there is a Symbolic Link anywhere in the path,
     * only if the specific file is.
     * <p>
     * <b>Note:</b> the current implementation always returns {@code false} if the system
     * is detected as Windows using {@link FilenameUtils#isSystemWindows()}
     * 
     * @param file the file to check
     * @return true if the file is a Symbolic Link
     * @throws IOException if an IO error occurs while checking the file
     * @since 2.0
     */
    public static boolean isSymlink(File file) throws IOException {
        if (file == null) {
            throw new NullPointerException("File must not be null");
        }
        if (isSystemWindows()) {
            return false;
        }
        File fileInCanonicalDir = null;
        if (file.getParent() == null) {
            fileInCanonicalDir = file;
        } else {
            File canonicalDir = file.getParentFile().getCanonicalFile();
            fileInCanonicalDir = new File(canonicalDir, file.getName());
        }
        
        if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) {
            return false;
        } else {
            return true;
        }
    }
    
    
    /**
     * Determines if Windows file system is in use.
     * 
     * @return true if the system is Windows
     */
    static boolean isSystemWindows() {
        return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
    }
    
    /**
     * Cleans a directory without deleting it.
     *
     * @param directory directory to clean
     * @throws IOException in case cleaning is unsuccessful
     */
    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        File[] files = directory.listFiles();
        if (files == null) {  // null if security restricted
            throw new IOException("Failed to list contents of " + directory);
        }

        IOException exception = null;
        for (File file : files) {
            try {
                forceDelete(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }
    
    /**
     * Deletes a file. If file is a directory, delete it and all sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>You get exceptions when a file or directory cannot be deleted.
     *      (java.io.File methods returns a boolean)</li>
     * </ul>
     *
     * @param file  file or directory to delete, must not be {@code null}
     * @throws NullPointerException if the directory is {@code null}
     * @throws FileNotFoundException if the file was not found
     * @throws IOException in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file, true);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent){
                    throw new FileNotFoundException("File does not exist: " + file);
                }
                String message =
                    "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }
}
